//
//  NetLoadAreaPickerViewController.m
//  KangChiLianMeng
//
//  Created by apple on 2018/6/8.
//  Copyright © 2018年 com.ruanmeng.login. All rights reserved.
//

#import "NetLoadAreaPickerViewController.h"

@interface NetLoadAreaPickerViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    UIView *_backView;
}
@property (nonatomic,retain)NSMutableArray * provinceArray;//省数组
@property (nonatomic,retain)NSMutableArray * cityArray;//市数组
@property (nonatomic,retain)NSMutableArray * districtArray;//区数组
@property (nonatomic,retain)UIView * toolView;//放取消和确认按钮的视图
@property (nonatomic,retain)NSString * provinceName;//省名字
@property (nonatomic,retain)NSString * provinceCode;//省编号
@property (nonatomic,retain)NSString * cityName;//市名字
@property (nonatomic,retain)NSString * cityCode;//市编号
@property (nonatomic,retain)NSString * districtName;//区名字
@property (nonatomic,retain)NSString * districtCode;//区编号

@end

@implementation NetLoadAreaPickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    backView.frame = CGRectMake(0, kScreen_Height - 260, kScreen_Width, 260);
    _backView = backView;
    [backView addSubview:self.toolView];
    
    [self getProvinceData];
}
- (NSMutableArray *)provinceArray
{
    if (!_provinceArray)
    {
        _provinceArray = [[NSMutableArray alloc]init];
    }
    return _provinceArray;
}

- (NSMutableArray *)cityArray
{
    if (!_cityArray)
    {
        _cityArray = [[NSMutableArray alloc]init];
    }
    return _cityArray;
}
- (NSMutableArray *)districtArray
{
    if (!_districtArray)
    {
        _districtArray = [[NSMutableArray alloc]init];
    }
    return _districtArray;
}
#pragma mark -- 初始化tollView
- (UIView *)toolView
{
    if (!_toolView)
    {
        _toolView = [[UIView alloc]init];
        _toolView.frame = CGRectMake(0, 0, kScreen_Width, 40);
        _toolView.backgroundColor = [UIColor colorWithHex:0xEBEBEB];
        [_toolView addSubview:self.canCleBtn];
        [_toolView addSubview:self.finishBtn];
        [_toolView addSubview:self.titleLab];
    }
    return _toolView;
}
#pragma mark -- 标题
- (UILabel *)titleLab
{
    if (!_titleLab)
    {
        _titleLab = [[UILabel alloc]init];
        _titleLab.font = [UIFont systemFontOfSize:13];
        _titleLab.frame = CGRectMake(_canCleBtn.right, 0, kScreen_Width - 20 - _canCleBtn.width - _finishBtn.width, 40);
        _titleLab.textAlignment = NSTextAlignmentCenter;
        _titleLab.text = @"";
        _titleLab.textColor = KTEXTCOLOR;
    }
    return _titleLab;
}
#pragma mark -- 初始化取消按钮
- (UIButton *)canCleBtn
{
    if (!_canCleBtn)
    {
        _canCleBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:20];
        label.text = @"取消";
        [label sizeToFit];
        _canCleBtn.frame = CGRectMake(20 , 0, label.size.width, 40);
        [_canCleBtn setTitle:@"取消" forState:(UIControlStateNormal)];
        [_canCleBtn setTitleColor:K666666 forState:(UIControlStateNormal)];
        _canCleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_canCleBtn addTarget:self action:@selector(canCleBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _canCleBtn;
}

#pragma mark -- 初始化确认按钮
- (UIButton *)finishBtn
{
    if (!_finishBtn)
    {
        _finishBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:20];
        label.text = @"确认";
        [label sizeToFit];
        _finishBtn.frame = CGRectMake(kScreen_Width - 20 - label.size.width, 0, label.size.width, 40);
        [_finishBtn setTitle:@"确认" forState:(UIControlStateNormal)];
        [_finishBtn setTitleColor:K666666 forState:(UIControlStateNormal)];
        _finishBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_finishBtn addTarget:self action:@selector(finishBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
        _finishBtn.hidden = YES;
    }
    return _finishBtn;
}

#pragma mark -- 初始化pickerView
- (UIPickerView *)pickerView
{
    if (!_pickerView)
    {
        _pickerView = [[UIPickerView alloc]init];
        _pickerView.frame = CGRectMake(0, _toolView.bottom, kScreen_Width, 220);
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = [UIColor whiteColor];
        [_backView addSubview:_pickerView];
    }
    return  _pickerView;
}

#pragma mark  -- pickerView代理方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
    {
        return _provinceArray.count;
    }
    else if (component == 1)
    {
        return _cityArray.count;
    }
    else if (component == 2)
    {
        return _districtArray.count;
    }
    else
    {
        return 0;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0)
    {
        NSLog(@"省：：：%@",[NSString stringWithFormat:@"%@",[[self.provinceArray safeObjectAtIndex:row] objectForKey:@"areaName"]]);
        if (self.provinceArray.count > 0)
        {
            _provinceName = [NSString stringWithFormat:@"%@",[[self.provinceArray safeObjectAtIndex:0] objectForKey:@"areaName"]];
            _provinceCode = [NSString stringWithFormat:@"%@",[[self.provinceArray safeObjectAtIndex:0] objectForKey:@"id"]];
        }
        return [NSString stringWithFormat:@"%@",[[self.provinceArray safeObjectAtIndex:row] objectForKey:@"areaName"]];
        
    }
    else if (component == 1)
    {
        NSLog(@"市：：：%@",[NSString stringWithFormat:@"%@",[[self.cityArray safeObjectAtIndex:row] objectForKey:@"areaName"]]);
        if (self.cityArray.count > 0)
        {
            _cityName = [NSString stringWithFormat:@"%@",[[self.cityArray safeObjectAtIndex:0] objectForKey:@"areaName"]];
            _cityCode = [NSString stringWithFormat:@"%@",[[self.cityArray safeObjectAtIndex:0] objectForKey:@"id"]];
        }
        return [NSString stringWithFormat:@"%@",[[self.cityArray safeObjectAtIndex:row] objectForKey:@"areaName"]];
    }
    else if (component == 2)
    {
        NSLog(@"区：：：%@",[NSString stringWithFormat:@"%@",[[self.districtArray safeObjectAtIndex:row] objectForKey:@"areaName"]]);
        if (self.districtArray.count > 0)
        {
            _districtName = [NSString stringWithFormat:@"%@",[[self.districtArray safeObjectAtIndex:0] objectForKey:@"areaName"]];
            _districtCode = [NSString stringWithFormat:@"%@",[[self.districtArray safeObjectAtIndex:0] objectForKey:@"id"]];
        }
        return [NSString stringWithFormat:@"%@",[[self.districtArray safeObjectAtIndex:row] objectForKey:@"areaName"]];
    }
    else
    {
        return nil;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.textColor = KTEXTCOLOR;
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:13]];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    NSLog(@"省市区::::%@",[self pickerView:pickerView titleForRow:row forComponent:component]);
    return pickerLabel;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        if (self.provinceArray.count > 0)
        {
            _provinceName = [NSString stringWithFormat:@"%@",[[self.provinceArray safeObjectAtIndex:row] objectForKey:@"areaName"]];
            _provinceCode = [NSString stringWithFormat:@"%@",[[self.provinceArray safeObjectAtIndex:row] objectForKey:@"id"]];
        }
        _cityName = @"";
        _districtName = @"";
        _cityCode = @"";
        _districtCode = @"";
        _finishBtn.hidden = YES;
        [self.cityArray removeAllObjects];
        [self.districtArray removeAllObjects];
//        [pickerView reloadComponent:1];
//        [pickerView reloadComponent:2];
        [self getCityDataWithAreaId:[NSString stringWithFormat:@"%@",[[self.provinceArray safeObjectAtIndex:row] objectForKey:@"id"]]];
    }
    if (component == 1) {
        
        if (self.cityArray.count > 0)
        {
            _cityName = [NSString stringWithFormat:@"%@",[[self.cityArray safeObjectAtIndex:row] objectForKey:@"areaName"]];
            _cityCode = [NSString stringWithFormat:@"%@",[[self.cityArray safeObjectAtIndex:row] objectForKey:@"id"]];
        }
        _finishBtn.hidden = YES;
        _districtCode = @"";
        _districtName = @"";
        [self.districtArray removeAllObjects];
        //[pickerView reloadComponent:2];
        [self getDistrictDataWithAreaId:[NSString stringWithFormat:@"%@",[[self.cityArray safeObjectAtIndex:row] objectForKey:@"id"]]];
    }
    
    if (component == 2) {
        if (self.districtArray.count > 0)
        {
            _districtName = [NSString stringWithFormat:@"%@",[[self.districtArray safeObjectAtIndex:row] objectForKey:@"areaName"]];
            _districtCode = [NSString stringWithFormat:@"%@",[[self.districtArray safeObjectAtIndex:row] objectForKey:@"id"]];
        }
    }
    
    
    
    
}

#pragma mark  ############# 获取省市区接口
#pragma mark -- 获取省数据接口
- (void)getProvinceData
{
    [NetWorkTool GET:getProvince param:nil success:^(id dic) {
        
    } other:^(id dic) {
        NSLog(@"省other：：：%@",dic);
        [self.provinceArray removeAllObjects];
        if (![[dic objectForKey:@"data"] isKindOfClass:[NSArray class]]) {
            //如果不是数组
            [self showOnleText:@"无省级数据" delay:1];
            return;
        }
        [self.provinceArray addObjectsFromArray:[dic objectForKey:@"data"]];;
        [self.pickerView reloadComponent:0];
        [self.pickerView selectRow:0 inComponent:0 animated:YES];
        [self getCityDataWithAreaId:[[self.provinceArray safeObjectAtIndex:0] objectForKey:@"id"]];
    } fail:^(NSError *error) {
    } needUser:NO];
}
#pragma mark -- 获取市数据接口
- (void)getCityDataWithAreaId:(NSString *)areaId
{
    NSDictionary * forParameters = [[NSDictionary alloc]initWithObjectsAndKeys:areaId,@"id",nil];
    [NetWorkTool GET:getSysDtAreasByParId param:forParameters success:^(id dic) {
        
    } other:^(id dic) {
        [self.cityArray removeAllObjects];
        if (![[dic objectForKey:@"data"] isKindOfClass:[NSArray class]]) {
            //如果不是数组
            [self showOnleText:@"无市级数据" delay:1];
            return;
        }
        [self.cityArray addObjectsFromArray:[dic objectForKey:@"data"]];;
        [self.pickerView reloadComponent:1];
        if (self.cityArray.count == 0) {
            //防止 钓鱼岛,无市县数据,而崩溃.并且清除区县数据,并刷新
            [self.districtArray removeAllObjects];
            [self.pickerView reloadComponent:2];
        } else {
            [self.pickerView selectRow:0 inComponent:1 animated:YES];
            //获取县级数据
            [self getDistrictDataWithAreaId:[[self.cityArray safeObjectAtIndex:0] objectForKey:@"id"]];
        }
    } fail:^(NSError *error) {
        
    } needUser:NO];
}

#pragma mark -- 获取区数据接口
- (void)getDistrictDataWithAreaId:(NSString *)areaId
{
    NSDictionary * forParameters = [[NSDictionary alloc]initWithObjectsAndKeys:areaId,@"id",nil];
    [NetWorkTool GET:getSysDtAreasByParId param:forParameters success:^(id dic) {
        
    } other:^(id dic) {
        [self.districtArray removeAllObjects];
        self->_finishBtn.hidden = NO;
        if (![[dic objectForKey:@"data"] isKindOfClass:[NSArray class]]) {
            //如果不是数组
            [self showOnleText:@"无区县数据" delay:1];
            return;
        }
        [self.districtArray addObjectsFromArray:[dic objectForKey:@"data"]];;
        [self.pickerView reloadComponent:2];
        if (self.districtArray.count == 0) {
            //防止 钓鱼岛,无市县数据,而崩溃
        } else {
            [self.pickerView selectRow:0 inComponent:2 animated:YES];
        }
    } fail:^(NSError *error) {
        
    } needUser:NO];
    
}
#pragma mark -- 判断是否是字符串
- (BOOL)judgeIsString:(id)type
{
    if ([type isKindOfClass:[NSString class]])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark -- 完成按钮点击事件
- (void)finishBtnClick
{
    if ([self anySubViewScrolling:self.pickerView]) {
        return;
    }
    NSLog(@"current date pick %@%@%@",_provinceName,_cityName,_districtName);
    NSLog(@"current date pick %@%@%@",_provinceCode,_cityCode,_districtCode);
    _provinceName = [NSString stringWithFormat:@"%@", _provinceName];
    _cityName = [NSString stringWithFormat:@"%@", _cityName];
    _districtName = [NSString stringWithFormat:@"%@", _districtName];
    _provinceCode = [NSString stringWithFormat:@"%@", _provinceCode];
    _cityCode = [NSString stringWithFormat:@"%@", _cityCode];
    _districtCode = [NSString stringWithFormat:@"%@", _districtCode];
    NetLoadAreaModel *areaModel = [NetLoadAreaModel initWithProvinceCode:_provinceCode provinceName:_provinceName cityCode:_cityCode cityName:_cityName districtCode:_districtCode districtName:_districtName];
    if (self.selectedBlock) {
        self.selectedBlock(areaModel);
    }
    if ([self.delegate respondsToSelector:@selector(getAddressStringWithProvinceName:cityName:districtName:provinceCode:cityCode:districtCode:)])
    {
        [self.delegate getAddressStringWithProvinceName:_provinceName cityName:_cityName districtName:_districtName provinceCode:_provinceCode cityCode:_cityCode districtCode:_districtCode];
    }
    [self canCleBtnClick];
}
#pragma mark -- 取消按钮点击事件
- (void)canCleBtnClick
{
    [UIView animateWithDuration:0.2 animations:^{
        [self.view setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
        _toolView.frame = CGRectMake(0,kScreen_Height + YY_bottomViewHeight,kScreen_Width, _toolView.height);
        self.pickerView.frame = CGRectMake(0, kScreen_Height + 40 + YY_bottomViewHeight, kScreen_Width, self.pickerView.height);
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            
        }];
    }];

}
- (BOOL)anySubViewScrolling:(UIView *)view{
    if ([view isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)view;
        if (scrollView.dragging || scrollView.decelerating) {
            return YES;
        }
    }
    for (UIView *theSubView in view.subviews) {
        if ([self anySubViewScrolling:theSubView]) {
            return YES;
        }
    }
    return NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
